#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <iostream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // Set up ThreadLogStream, which redirect cout to signal sendLogString
    // Set up  MessageHandler,  wgucg catch message from sendLogString and Display
    /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
    m_qd = new ThreadLogStream(std::cout); //Redirect Console output to QTextEdit
    this->msgHandler = new MessageHandler(this->ui->logText, this);
    connect(m_qd, &ThreadLogStream::sendLogString, msgHandler, &MessageHandler::catchMessage);
    /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
}

Widget::~Widget()
{
    delete ui;
}

void Widget::QMessageOutput(QtMsgType, const QMessageLogContext &, const QString &msg)
{
   std::cout<<msg.toStdString().c_str()<<std::endl;
}

void Widget::on_btn_SelectDbcfile_clicked()
{
    QString srcDirPath = ui->lineEdit_dbcFilePath->text();

    srcDirPath = QFileDialog::getOpenFileName(
        this, "选择要分析文件",
        srcDirPath,
        "二进制文件 (*.dbc *.bin);; 所有文件 (*.*);; ");

    if (!srcDirPath.isEmpty())
    {
        ui->lineEdit_dbcFilePath->setText( srcDirPath );
    }

}

void Widget::on_btn_analyse_clicked()
{
    ui->logText->clear();
    textbuf.clear();

    if( !ui->lineEdit_dbcFilePath->text().isEmpty() )
    {
        if( !ui->lineEdit_outCodeFilePath->text().isEmpty() )
        {
            if( !ui->lineEdit_DrvName->text().isEmpty()  )
            {
                QStringList strList;
                strList.append(ui->lineEdit_dbcFilePath->text());
                strList.append(ui->lineEdit_outCodeFilePath->text());
                strList.append(ui->lineEdit_DrvName->text());
                setStrOpts(strList);
                workThreadInit();
            }
        }
    }
}

void Widget::Append(const QString &text)
{
    // static QString textbuf;
    textbuf+=text;
    ui->logText->setText(textbuf);
}

void Widget::dealsigResult(QString, unsigned int)
{
    std::cout<< "dealsigResult" << std::endl;
}

void Widget::workThreadInit()
{
    QThread     *workerThread= new QThread;
    ThreadWorker *worker  = new ThreadWorker();
    worker->moveToThread(workerThread);
    connect(workerThread, SIGNAL(started()), worker, SLOT(doWork()));
    connect(worker, SIGNAL(finished()), workerThread, SLOT(quit()));

    connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
    connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater()));
    workerThread->start();
}


void Widget::on_btn_SelectOutCodeFilePath_clicked()
{
    QString srcDirPath = ui->lineEdit_outCodeFilePath->text();

    srcDirPath = QFileDialog::getExistingDirectory(
        this, "choose src Directory",
        srcDirPath);


    if (!srcDirPath.isEmpty())
    {
        ui->lineEdit_outCodeFilePath->setText( srcDirPath );
    }
}



